# coding:utf8
import paramiko
from  public.function import Public_loggining
from django.conf import settings 
import os 
class ServerParamikoMixin(Public_loggining,object):
    _client = None

    def __init__(self,ip="",port="",username="", *args, **kwargs):
        super(ServerParamikoMixin, self).__init__()
        self.ip=ip
        self.username=username
        self.port=port
        self.key_filename=os.path.join(settings.BASE_DIR,"cmdb/Identity.pub")


    def _get_client(self, password='', user='', **kwargs):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(self.ip, self.port, self.username, password='ljjpwd@123',
                       key_filename=self.key_filename,
                       allow_agent=True, look_for_keys=True, compress=False)
        print(self.ip, self.port, self.username)
        self._client = client
        return  self._client


    def p_exec_command(self, command, ignore_error=False, timeout=120, **kwargs):
        """
        命令默认执行120秒,超过超时
        使用paramiko和密码执行命令，如果key可以直接连接，密码错误也可以执行命令。。
        结果，类似getstatusoutput
        """
        self.log.debug('begin: %s' % command)

        ssh_client = self._get_client(**kwargs)
        # 捕获不到socket.timeout的异常。。。。。
        if command in settings.DANGEROUS_COMMAND:
            raise ValueError("不允许执行这些命令%s" %(command))

        stdin, stdout, stderr = ssh_client.exec_command(command, timeout=timeout)

        error = stderr.read()
        status = stdout.channel.recv_exit_status()
        if status != 0:
            self.log.warn('p_exec_command 执行命令出错: %s' % error)
            if ignore_error:
                # 忽略错误，只是不raise  Exception
                return (status, stdout.read())
            raise Exception('p_exec_command 执行命令出错: %s' % error)
        else:
            #self.log.debug('OK: %s' % command)
            return (status, stdout.read())
        ssh_client.quit()




class ServerMixin(ServerParamikoMixin,):
    pass




